/**
 * 
 */
package moviles.turnomovil.interfaz;

import java.util.Calendar;
import java.util.Date;

import moviles.app.mundo.R;
import moviles.turnomovil.mundo.AlertaService;
import moviles.turnomovil.mundo.TurnReceiver;
import moviles.turnomovil.mundo.TurnoMovil;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

/**
 * @author jj.villegas47 y ja.guevara907
 *
 */
public class TomarTurnoActivity extends Activity{
	
	private Button btnAyudaCodigo;
	
	private Button btnTomarTurno;
	
	private BroadcastReceiver receiver; 
	
	private int porcBateria;
	
	public final static String TURN_REQUEST = "*/TurnoMovil/*\n*/TURN_REQUEST/*\n*/*";
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.lytomarturno);
		initReceiver();
		initBotones();
	}

	private void initBotones() {
		
		btnAyudaCodigo = (Button) findViewById(R.id.btnAyudaCodigo);
		btnAyudaCodigo.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
			}
		});
		
		btnTomarTurno = (Button) findViewById(R.id.btnTomarTurno);
		btnTomarTurno.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				tomarTurno();
//				tomarTurnoPrueba();
			}
		});
		
	}
	
	protected void tomarTurnoPrueba() {
		
		if(porcBateria < 99){
			showBatteryAlertPrueba();
		}
		else {
			sendTurnRequestPrueba();
		}
	}
	
	private void sendTurnRequestPrueba() {
		int turno = 15; 
		double lambda = 5; 
		double k = 8; 
		
		double kFact = 1;
		for(int i = 1 ; i <= k ; i++){
			kFact = kFact*i;
		}
		double probaPoisson = (Math.pow(Math.E, -lambda)*Math.pow(lambda, k))/kFact;
		probaPoisson = Math.rint(probaPoisson*10000)/10000; 
		int tiempoSegEspera = 1;
		
		double proba = 1;
		
		while (proba>0.1){
			proba = Math.pow((1-probaPoisson),tiempoSegEspera);
			tiempoSegEspera++;
		}
		
		Calendar calendario = Calendar.getInstance();
		calendario.setTime(new Date());
		calendario.add(Calendar.MINUTE, tiempoSegEspera);
		
		TurnoMovil.getInstance().setTiempoEstimado(calendario);
		TurnoMovil.getInstance().setTurno(turno);
		startService( new Intent( this, AlertaService.class));
		Toast.makeText(this, "Tiempo Estimado: " + tiempoSegEspera + " minutos.", 4000).show();
		finish();
		
	}

	private void showBatteryAlertPrueba() {
		AlertDialog.Builder helpBuilder = new AlertDialog.Builder(this);
    	helpBuilder.setIcon(android.R.drawable.ic_lock_idle_low_battery);
    	helpBuilder.setTitle("Alerta: Bater�a baja!");
    	helpBuilder.setMessage("Perder� su turno si su dispositivo se apaga. \n Nivel de bater�a: "+porcBateria+"% \n\n �A�n desea tomar un turno?");
    	 
    	helpBuilder.setPositiveButton("Yes",
    	   new DialogInterface.OnClickListener() {

    	    public void onClick(DialogInterface dialog, int which) {
    	      sendTurnRequestPrueba();
    	    }
    	   });
    	
    	helpBuilder.setNegativeButton("No",
    	    	   new DialogInterface.OnClickListener() {

    	    	    public void onClick(DialogInterface dialog, int which) {
    	    	     // Do nothing but close the dialog
    	    	    }
    	    	   });

    	 AlertDialog helpDialog = helpBuilder.create();
    	 helpDialog.show();
		
	}

	protected void tomarTurno() {
		if(porcBateria < 60){
			showBatteryAlert();
		}
		else {
			sendTurnRequest();
		}
	
		// TODO Auto-generated method stub
		
	}
	
	private void sendTurnRequest(){
		EditText txtCodigo = (EditText)findViewById(R.id.txtIngresarCodigo);
		
		//Esto puede ser tambien un int, hay que evaluarlo
		String codigo = txtCodigo.getText().toString().trim();
        String message = TURN_REQUEST;              
        if (codigo.length()>0 && message.length()>0)                
        	sendSMS(codigo, message);                
        else
            Toast.makeText(getBaseContext(), "Please enter both phone number and message.", Toast.LENGTH_SHORT).show();
	}
	
    private void sendSMS(String phoneNumber, String message)
    {        
        PendingIntent pi = PendingIntent.getActivity(this, 0,
            new Intent(this, TomarTurnoActivity.class), 0);                
        SmsManager sms = SmsManager.getDefault();
        sms.sendTextMessage(phoneNumber, null, message, pi, null);  
        finish();
    }  
    
    private void showBatteryAlert() {
    	AlertDialog.Builder helpBuilder = new AlertDialog.Builder(this);
    	helpBuilder.setIcon(android.R.drawable.ic_lock_idle_low_battery);
    	helpBuilder.setTitle("Alerta: Bater�a baja!");
    	helpBuilder.setMessage("Perder� su turno si su dispositivo se apaga. \n Nivel de bater�a: "+porcBateria+"% \n\n �A�n desea tomar un turno?");
    	 
    	helpBuilder.setPositiveButton("Yes",
    	   new DialogInterface.OnClickListener() {

    	    public void onClick(DialogInterface dialog, int which) {
    	      sendTurnRequest();
    	    }
    	   });
    	
    	helpBuilder.setNegativeButton("No",
    	    	   new DialogInterface.OnClickListener() {

    	    	    public void onClick(DialogInterface dialog, int which) {
    	    	     // Do nothing but close the dialog
    	    	    }
    	    	   });

    	 AlertDialog helpDialog = helpBuilder.create();
    	 helpDialog.show();

    	}
	
    private void initReceiver() {
		receiver = new BroadcastReceiver(){

			@Override
			public void onReceive(Context context, Intent intent) {
				
				int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
				
				int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, 100);
				
				porcBateria = (level*100)/scale;
			}
			
		};
		
		this.registerReceiver(receiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
	}
}
